package org.panxiong.openapi.utils;

import java.io.File;
import java.util.Arrays;

/**
 * 获取Spring-Boot的主包
 */
public class PackageUtils {

    private String appBasePackage;

    private String outputDirectory;

    public String getAppBasePackage() {
        return getAppBasePackage("/target/classes");
    }

    public String getAppBasePackage(String outputDirectory) {
        this.outputDirectory = outputDirectory;
        if (appBasePackage == null) {
            initBasePackage(new File(outputDirectory));
        }
        return appBasePackage;
    }

    private void initBasePackage(File file) {
        if (!file.isDirectory()) {
            return;
        }
        File[] listFiles = file.listFiles();
        if (listFiles == null || listFiles.length <= 0) {
            appBasePackage = file.getAbsolutePath().replace(outputDirectory + File.separator, "");
        } else {
            boolean allMatchClass = Arrays.stream(listFiles).anyMatch(it -> it.getName().endsWith(".class"));
            if (!allMatchClass) {
                for (File listFile : listFiles) {
                    initBasePackage(listFile);
                }
            } else {
                appBasePackage = file.getAbsolutePath().replace(outputDirectory + File.separator, "");
            }
        }
        appBasePackage = appBasePackage.replace(File.separator, ".").trim();
    }

    public static String getBasePackage(String outputDirectory) {
        return new PackageUtils().getAppBasePackage(outputDirectory);
    }
}
